package com.ybwh.springboot2.common.jackson.enumat;

import com.ybwh.springboot2.common.enums.CodeTextEnum;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


/**
 *  自定义的校验注解验证类
 *
 */
public class EnumFieldValidator implements ConstraintValidator<EnumField, Object> {


    private EnumField enumField;

    @Override
    public void initialize(EnumField enumField) {
        this.enumField = enumField;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return Boolean.TRUE;
        }

        if (enumField.value() == null) {
            return Boolean.TRUE;
        }



        //重写错误提示
//        context.disableDefaultConstraintViolation();
//        context.buildConstraintViolationWithTemplate("手机号码1 身份证号码，手机号码1，邮箱1三者中至少要有一个")
//                .addPropertyNode("id_card").addConstraintViolation();


        if(StringUtils.isBlank(enumField.message())){
            //重写错误提示
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("值不对，值范围："+CodeTextEnumUtils.getDscr(enumField.value())).addConstraintViolation();
        }

        String displayName = CodeTextEnumUtils.getDisplayName(enumField.value(), value);
        if (null != displayName) {
            return true;
        }


        return false;
    }
}
